package com.placement.refresh.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.placement.refresh.exception.RefreshRuntimeException;

/**
 * purpose: This class is utility class 
 * 
 * @author Amit Chadha
 *
 */
public class RefreshUtil {

	private static final Log logger = LogFactory.getLog(RefreshUtil.class);
	
	/**
	 * purpose: This method copy client information to given client by looking same client by UCN in client List 
	 * 
	 * @param clientList		:clientBVO List
	 * @param clientBVO 		:clientBVO object
	 * @param primaryClientOID	:clientOid
	 */
	
	
	public static String getDateAsString(Date date){
		String strDate = "";
//		logger.debug(">>getDateAsString>> date:"+ date);
		if(date!=null){
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
			strDate = sdf.format(date);
		}
		return strDate;
	}
	
	public static String getDateAsStringDateTime(Date date){
		String strDate = "";
		if(date!=null){
			try{
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
			strDate = sdf.format(date);
			}catch(Exception e){
				logger.error(">>getDateAsStringDateTime>>",e);
			}
		}
		return strDate;
	}
	
	/**
	 * @param mailSubject
	 * @param mailBody
	 * @return
	 * @throws Exception
	 */
	public static int sendRefreshMail(String mailSubject, String mailBody,String emailAddresses) throws Exception {

		int returnValue = 0;
		
		logger.debug(
			"\n**** Executing sendLOLAMail() with parameters: "
				+ " mailSubject: " + mailSubject
				+ " mailBody: " + mailBody
				);
		
//		/*-- file.separator returns \ for Windows & / for Unix */
		String mailHost = RefreshProperites.getProperty("LOLA_EMAIL_HOST");
		//String emailAddresses = RefreshProperites.getProperty("LOLA_EMAIL_ADDRESSES");
		String emailSender = RefreshProperites.getProperty("LOLA_EMAIL_SENDER");
		
		// EMail            
			if (emailAddresses != null && mailSubject != null && mailBody != null) {
				logger.info("Email to: " + emailAddresses);

				MailController mailController = new MailController(emailAddresses, emailSender, mailSubject);
				mailController.setHost(mailHost);
				
				mailController.setBodyText(mailBody);
				mailController.sendMail();
								
					logger.debug(
						"Sent email for Batch to: "
							+ emailAddresses
							+ " Subject: " + mailSubject + "\n Body: " + mailBody);
			} else {
				if (mailHost == null) {
					logger.info("***********************************************************");
					logger.info("* Mail host not specified for LOLA Batch**");
					logger.info("***********************************************************");
					returnValue = 9;
				}
				if (emailAddresses == null) {
					logger.info("**************************************************************");
					logger.info("* No Email address specified for LOLA Batch**");
					logger.info("**************************************************************");
					returnValue = 9;
				}
				if (mailSubject == null) {
					logger.info("******************************************************************");
					logger.info("* Email subject/body missing for LOLA Batch**");
					logger.info("******************************************************************");
				}
			}
			
		return returnValue;
	}	
	
	/**
	 * purpose: This method copy client information to given client by looking same client by clientOid in client List 
	 * 
	 * @param clientList		:clientBVO List
	 * @param clientBVO 		:clientBVO 
	 */
		
	/**
	 * Purppose: This method return processId for given processName
	 * 
	 * @param processName	:String processName
	 * @return				:int processId
	 */
	public static int getProcessId(String processName){
		int processId = -1;
		for(int idx=0; idx<Constants.CONTROL_STEP.length;idx++){
			System.out.println(Constants.CONTROL_STEP[idx][1]);
			if(processName.equals(Constants.CONTROL_STEP[idx][1])){
				processId = Integer.parseInt(Constants.CONTROL_STEP[idx][0]);
				System.out.println(processId);
				break;
			}
			
		}
		if(processId==-1){
			logger.error(">>getProcessId:Invalid Proces name:"+ processName);
			throw new RefreshRuntimeException("getProcessId>> Invalid ProcessName:"+processName);
		}
		return processId;
	}
	
	public static int getProcessIdByClassName(String className){
		int processId = -1;
		for(int idx=0; idx<Constants.CONTROL_STEP.length;idx++){
			if(className.equals(Constants.CONTROL_STEP[idx][3])){
				processId = Integer.parseInt(Constants.CONTROL_STEP[idx][0]);
				break;
			}
		}
		/*if(processId==-1){
			logger.error(">>getProcessId:Invalide Proces name:"+ className);
			throw new RefreshRuntimeException("getProcessId>> Invalid className:"+className);
		}*/
		return processId;
	}
	
	public static String getProcessNameByClassName(String className){
		String processName = null;
		for(int idx=0; idx<Constants.CONTROL_STEP.length;idx++){
			if(className.equals(Constants.CONTROL_STEP[idx][3])){
				processName = Constants.CONTROL_STEP[idx][1];
				break;
			}
		}
		/*if(processName==""){
			logger.error(">>getProcessId:Invalide Proces name:"+ className);
			throw new RefreshRuntimeException("getProcessId>> Invalid className:"+className);
		}*/
		return processName;
	}


	public static void printLongArrayList(ArrayList<Long> removedPositionKeys) {
		String str = "";
		for(int idx=0; idx<removedPositionKeys.size(); idx++){
			str = str+ removedPositionKeys.get(idx).longValue()+",";
//			logger.debug("value("+idx+"):"+removedPositionKeys.get(idx).longValue());
		}
		logger.debug(str);
	}


	public static void addToMap(HashMap<Object,ArrayList> map, Object key, Object object, boolean chkDuplicate) {
		if(map.get(key)==null){
			ArrayList arlList =new ArrayList();
			map.put(key, arlList);
		}
		ArrayList arlList = map.get(key);
		if(!chkDuplicate || !arlList.contains(object)){
			arlList.add(object);
		}
	}

	
	/** When an exception occurs, this code snippet will print the stack trace 
     * of the exception to a string. 
     * This way, the exception stack trace at runtime can be recorded in log file. 
     * @author Anirudha J
     * @param t
     * @return 	
     */
    public static String getStackTrace(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        t.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
}
